package XML;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class test1 {
    //1、将xml加载到内存，生成dom对象
    Document document = null;
    public void getDocument() {
        //创建一个构造器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            //创建一个构造器
            DocumentBuilder builder = factory.newDocumentBuilder();
            //加载xml
            document = builder.parse(this.getClass().getResourceAsStream("/XML/phone.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void show(){
        NodeList brands = document.getElementsByTagName("Brand");
        for (int i = 0; i < brands.getLength(); i++) {
            Node brand = brands.item(i);//获取集合中的节点
            Element brandElement = (Element)brand;//强转
            String type = brandElement.getAttribute("name");
            System.out.println(type);
            //获取孩子
            NodeList types = brandElement.getChildNodes();
            for (int j = 0; j < types.getLength(); j++) {
                Node t = types.item(j);
                if(t.getNodeType() == Node.ELEMENT_NODE){
                    Element tpyeElement = (Element)t;//强转
                    System.out.println(tpyeElement.getAttribute("name"));

                }

            }
        }

    }
    public void add(){
        //创建节点
        Element type = document.createElement("Type");
        type.setAttribute("name","note4");
        Element brand = document.createElement("Brand");
        brand.setAttribute("name","三星");
        //父亲追加孩子
        brand.appendChild(type);
        document.getElementsByTagName("PhoneInfo").item(0).appendChild(brand);
    }

    public static void main(String[] args) {
        test1 t = new test1();
        t.getDocument();
        t.show();
        System.out.println("-------------------");
        t.add();
        t.show();
    }
}
